﻿using UnityEngine;
using System.Collections;
using System.IO;

namespace LuaInterface {
    /// <summary>
    /// 集成自LuaFileUtils，重写里面的ReadFile，
    /// </summary>
    public class LuaLoader : LuaFileUtils {

        // Use this for initialization
        public LuaLoader() {
            instance = this;
            beZip = LuaConst.LuaBundleMode;
        }

        /// <summary>
        /// 添加打入Lua代码的AssetBundle
        /// </summary>
        /// <param name="bundle"></param>
        public void AddBundle(string bundleName) {
            string url = Util.DataPath + bundleName.ToLower();
            if (File.Exists(url)) {
                var bytes = File.ReadAllBytes(url);
                AssetBundle bundle = AssetBundle.LoadFromMemory(bytes);
                if (bundle != null)
                {
                    bundleName = bundleName.Replace("lua/", "").Replace(".unity3d", "");
                    base.AddSearchBundle(bundleName.ToLower(), bundle);
                }
            }
			else
			{
				url = Application.persistentDataPath + "/"+ bundleName.ToLower();
				if(File.Exists(url)){
					var bytes = File.ReadAllBytes(url);
					AssetBundle bundle = AssetBundle.LoadFromMemory(bytes);
					if (bundle != null)
					{
						bundleName = bundleName.Replace("lua/", "").Replace(".unity3d", "");
						base.AddSearchBundle(bundleName.ToLower(), bundle);
					}
				}
			}
        }

        /// <summary>
        /// 当LuaVM加载Lua文件的时候，这里就会被调用，
        /// 用户可以自定义加载行为，只要返回byte[]即可。
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public override byte[] ReadFile(string fileName) {
            return base.ReadFile(fileName);     
        }


		protected override byte[] ReadZipFile(string fileName)
		{
			byte[] bytes = base.ReadZipFile(fileName);
			if(bytes==null){
				string temp = fileName.ToLower() + ".lua";
				temp = "lua/lua_" + System.IO.Path.GetDirectoryName(temp).Replace("/","_");
				if(!zipMap.ContainsKey(temp)){
					AddBundle(temp.ToLower()+".unity3d");
				}
				bytes = base.ReadZipFile(fileName); 
			}
			return bytes;
		}

    }
}